package com.baiku.sanhos.controller;

import com.baiku.sanhos.mapper.AdminMapper;
import com.baiku.sanhos.pojo.dto.AdminLoginDTO;
import com.baiku.sanhos.pojo.dto.AdminSendDTO;
import com.baiku.sanhos.pojo.vo.AdminVo;
import com.baiku.sanhos.response.ResultVO;
import com.baiku.sanhos.response.StatusCode;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@Api(tags = "管理员管理")
@RequestMapping("/pa/admin")
public class AdminController {

    @Autowired
    private AuthenticationManager manager;

    @Autowired
    private AdminMapper adminMapper;

    @PostMapping("/login")
    public ResultVO login(@RequestBody AdminLoginDTO adminLoginDTO){
        String username = adminLoginDTO.getUsername()+adminLoginDTO.getFlag();
        Authentication result = manager.authenticate(new UsernamePasswordAuthenticationToken(
                username,adminLoginDTO.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(result);
        return ResultVO.ok(result.getPrincipal());
    }

    @PostMapping("/msLogin")
    public ResultVO msLogin(@RequestBody AdminSendDTO adminSendDTO){
        if(adminSendDTO!=null){
            AdminVo adminVo = adminMapper.selectByPhone(adminSendDTO.getPhone());
            if(adminSendDTO.getCode().equals(adminSendDTO.getVerificationCode())){
                String flag = String.valueOf(adminSendDTO.getFlag());
                String phone = String.valueOf(adminSendDTO.getPhone());
                String phones = phone+flag;
                Authentication result = manager.authenticate(new UsernamePasswordAuthenticationToken(
                        phones,adminVo.getPassword()));
                SecurityContextHolder.getContext().setAuthentication(result);
                return ResultVO.ok(result.getPrincipal());
            }else {
                return ResultVO.ok(StatusCode.CODE_ERROR);
            }
           /* Long phone1 = admin.getPhone();
            if(phone.equals(phone1)){
               return ResultVO.ok(admin);
            }*/

        }
        return ResultVO.ok(StatusCode.USERNAME_ALREADY_EXISTS);
    }


}
